package com.fyh.service.impl;

import com.fyh.constant.MessageConstant;
import com.fyh.entity.chat.SimpleContact;
import com.fyh.entity.common.Result;
import com.fyh.entity.community.PostVO;
import com.fyh.entity.community.ReplyVO;
import com.fyh.entity.job.DeliveryRecord;
import com.fyh.entity.user.SimpleCandidate;
import com.fyh.entity.user.User;
import com.fyh.entity.user.UserLogin;
import com.fyh.entity.user.Vitae;
import com.fyh.feign.UserCandidateFeignClient;
import com.fyh.feign.UserChatFeignClient;
import com.fyh.feign.UserJobFeignClient;
import com.fyh.mapper.UserMapper;
import com.fyh.service.UserService;
import com.fyh.util.JwtUtil;
import com.fyh.util.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Qualifier("com.fyh.feign.UserJobFeignClient")
    @Autowired
    UserJobFeignClient userJobFeignClient;
    @Qualifier("com.fyh.feign.UserCandidateFeignClient")
    @Autowired
    UserCandidateFeignClient userCandidateFeignClient;
    @Qualifier("com.fyh.feign.UserChatFeignClient")
    @Autowired
    UserChatFeignClient userChatFeignClient;
    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public UserLogin login(UserLogin user) {
        //对密码进行md5加密
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        log.info("用户登录：{}", user);
        //通过用户名和密码查询用户是否存在，并返回用户类型，添加到JWT载荷中
        user = userMapper.login(user);
        if(user != null){
            //存在就返回JWT令牌
            user.setToken(JwtUtil.createJwt(user.getUserId(), user.getUserType()));
            user.setUsername(null);
            user.setPassword(null);
        }
        log.info("用户登录：{}", user);
        // 更新用户在线状态
        userMapper.updateStatus(user.getUserId());

        return user;
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Transactional
    @Override
    public String register(User user) {
        //查询用户名是否已存在
        if(userMapper.selectByUsername(user.getUsername()) != null){
            return MessageConstant.USERNAME_IS_EXIST;
        }
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        user.setAvatarPath("https://photo.fanya.chaoxing.com/photo_80.jpg");
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
        //生成用户昵称
        user.setNickname(user.getUserType() + "_" + user.getUserId());
        userMapper.update(user);
        //自动创建一个空简历
        if(user.getUserType().equals("candidate")){
            Vitae vitae = new Vitae();
            vitae.setUserId(user.getUserId());
            vitae.setCreateTime(LocalDateTime.now());
            vitae.setUpdateTime(LocalDateTime.now());

            userCandidateFeignClient.insertVitae(vitae);
        }
        return null;
    }

    /**
     * 获取用户信息
     * @param id
     * @return
     */
    @Override
    public User getUserInfo(Long id) {
        // 获取用户基本信息
        User user = userMapper.selectById(id);
        user.setPassword(null);
        // 获取用户偏好地址
        user.setPreferredAddresses(userMapper.selectPreferredAddresses(user.getUserId()));
        return user;
    }

    /**
     * 获取标签列表
     * @return
     */
    @Override
    public Map<String, List<String>> getTagList() {
        Result<Map<String, List<String>>> result = userJobFeignClient.getTagList();
        return result.getData();
    }

    /**
     * 获取用户昵称
     * @param id
     * @return
     */
    @Override
    public String getNickname(Long id) {
        String nickname = userMapper.selectNicknameById(id);
        return nickname;
    }

    /**
     * 更新用户信息
     * @param user
     */
    @Override
    @Transactional
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        //更新用户信息
        userMapper.update(user);
        //更新用户偏好地址
        userMapper.deletePreferredAddresses(user.getUserId());
        for (String address : user.getPreferredAddresses()) {
            userMapper.insertPreferredAddresses(user.getUserId(), address);
        }
    }

    /**
     * 上传用户头像
     * @param file
     */
    @Override
    public String uploadAvatar(MultipartFile file) {
        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成新的文件名
            String fileName = UUID.randomUUID() + suffix;
            // 上传文件
            String filePath = OssUtil.uploadFile(fileName, file.getBytes());
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取用户简历
     * @param userId
     * @return
     */
    @Override
    public Vitae getUserVitae(Long userId) {
        // 获取用户简历
        Result<Vitae> vitae = userCandidateFeignClient.getUserVitae(userId);
        return vitae.getData();
    }

    /**
     * 获取职位求职者基础信息列表
     * @param deliveryRecordList
     */
    @Override
    public List<SimpleCandidate> getSimpleCandidateList(List<DeliveryRecord> deliveryRecordList) {
        List<SimpleCandidate> simpleCandidateList = new ArrayList<>();
        for(DeliveryRecord deliveryRecord : deliveryRecordList){
            //获取职位求职者基础信息
            SimpleCandidate simpleCandidate = userMapper.getSimpleCandidate(deliveryRecord.getUserId());
            //获取职位求职者标签
            simpleCandidate.setTags(userCandidateFeignClient.getTagNameListByUserId(deliveryRecord.getUserId()).getData());
            //添加投递时间
            simpleCandidate.setCreateTime(deliveryRecord.getCreateTime());
            //添加投递状态
            simpleCandidate.setStatus(deliveryRecord.getStatus());
            simpleCandidateList.add(simpleCandidate);
        }
        return simpleCandidateList;
    }

    /**
     * 获取职位求职者基础信息
     * @param userId
     * @return
     */
    @Override
    public SimpleCandidate getSimpleCandidate(Long userId) {
        SimpleCandidate simpleCandidate = userMapper.getSimpleCandidate(userId);
        return simpleCandidate;
    }

    /**
     * 登出
     * @param userId
     */
    @Override
    public void logout(Long userId) {
        //修改用户状态
        userMapper.logout(userId);
    }

    /**
     * 补全联系人列表头像路径和用户在线状态
     * @param simpleContactList
     * @return
     */
    @Override
    public List<SimpleContact> getContactListAvatarPath(List<SimpleContact> simpleContactList) {
        for(SimpleContact simpleContact : simpleContactList){
            SimpleContact simpleContact1 = userMapper.getContactAvatarPath(simpleContact.getContactUserId());
            simpleContact.setAvatarPath(simpleContact1.getAvatarPath());
            simpleContact.setStatus(simpleContact1.getStatus());
        }
        return simpleContactList;
    }

    /**
     * 补全发布者昵称和头像路径（用户帖子列表）
     * @param postVOList
     * @return
     */
    @Override
    public List<PostVO> selectNicknameAndAvaterPathForPost(List<PostVO> postVOList) {
        for(PostVO postVO : postVOList){
            User user = userMapper.selectById(postVO.getUserId());
            postVO.setNickname(user.getNickname());
            postVO.setAvatarPath(user.getAvatarPath());
        }
        return postVOList;
    }

    /**
     * 补全发布者昵称和头像路径（用户回复列表）
     * @param replyVOList
     * @return
     */
    @Override
    public List<ReplyVO> selectNicknameAndAvaterPathForReply(List<ReplyVO> replyVOList) {
        for(ReplyVO replyVO: replyVOList){
            User user = userMapper.selectById(replyVO.getUserId());
            replyVO.setNickname(user.getNickname());
            replyVO.setAvatarPath(user.getAvatarPath());
            replyVO.setReplyNickname(userMapper.selectNicknameById(replyVO.getReplyUserId()));
        }
        return replyVOList;
    }
}
